﻿using Microsoft.Owin.Hosting;
using Serilog;
using System;
using System.Configuration;
using System.Windows.Forms;

namespace ybx_caller
{
    public partial class FMainForm : Form
    {
        private IDisposable _webApp;

        public FMainForm()
        {
            InitializeComponent();

            Log.Logger = new LoggerConfiguration()
           .ReadFrom.AppSettings()
           .WriteTo.Sink(new RichTextBoxSink(logRichTextBox, null))
           .CreateLogger();
        }

        private void toolStripMenuItemShow_Click(object sender, EventArgs e)
        {
            showMainForm();
        }

        private void showMainForm()
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }

        private void toolStripMenuItemClose_Click(object sender, EventArgs e)
        {
            notifyIcon1.Visible = false;
            this.Close();
        }

        private void toolStripMenuItemMini_Click(object sender, EventArgs e)
        {
            this.Visible = false;
        }

        private void FMainForm_FormClosing(object sender, FormClosingEventArgs e)
        {

            if (e.CloseReason == CloseReason.UserClosing)
            {
                var result = MessageBox.Show(this, "医保接口服务正在运行中,退出后将无法调用医保服务,请问是否要退出?", "退出确认",
                                             MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == DialogResult.No)
                {
                    e.Cancel = true;
                }
                else
                {
                    StopWebServer();
                }
            }
        }

        private void FMainForm_Load(object sender, EventArgs e)
        {
            StartWebServer();
            toolStripStatusLabelIp.Text = $"IP:{NetworkUtils.GetLocalIPAddress()}";
        }

        private void StartWebServer()
        {
            string port = ConfigurationManager.AppSettings["ServerPort"];
            string ipAddress = "127.0.0.1";

#if !DEBUG
    // 在非Debug模式下使用实际的本地IP地址
    ipAddress = NetworkUtils.GetLocalIPAddress();
#endif

            string baseAddress = $"http://{ipAddress}:{port}/";

            _webApp = WebApp.Start<Startup>(url: baseAddress);
            Log.Information("Web Api Server running at " + baseAddress);
        }



        private void StopWebServer()
        {
            _webApp?.Dispose();
            Log.Information("Web Api Server shut down.");
        }

        private void FMainForm_Resize(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                Hide();
                ShowInTaskbar = false;
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            showMainForm();
        }
    }
}
